<template>
  <view class="app">
    <view class="main-box">
      /* #ifdef MP-WEIXIN || APP-PLUS */
      <view class="single-box" v-if="form.id == 0" @click="getWxAddress()">
        <view class="weixin-item">
          <view class="weixin-title">
            <u-icon class="mr-20rpx" size="33" color="#09bf63" name="weixin-fill"></u-icon>
            <text> 获取微信收货地址 </text>
          </view>
          <u-icon size="24rpx" color="#b7b7b7" name="arrow-right"></u-icon>
        </view>
      </view>
      /* #endif */

      <view class="form-box">
        <view class="form-item">
          <text class="item-title">收件人</text>
          <input type="text" v-model="form.receiver" placeholder="请输入收件人姓名" />
        </view>
        <view class="form-item">
          <text class="item-title">手机号码</text>
          <input type="text" v-model="form.phone" maxlength="11" placeholder="请输入收件人手机号码" />
        </view>

        <view class="form-item">
          <text class="item-title">所在地区</text>
          <view class="area-zone" @click="showRegion = true">
            <text v-if="regionStr">{{ regionStr }}</text>
            <text v-else class="input-placeholder">请选择地区</text>
            <u-icon class="right-icon" size="24" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
          <u-picker
            v-model="showRegion"
            mode="region"
            confirm-text="确认"
            :default-region="region"
            @confirm="changeRegion"
          ></u-picker>
        </view>
        <view class="form-item">
          <text class="item-title">详细地址</text>
          <input type="text" v-model="form.address" placeholder="请输入详细地址" />
        </view>
      </view>

      <!-- 智能识别 -->
      <view class="smart-box">
        <text class="smart-title">智能识别</text>
        <textarea
          class="smart-address"
          v-model="smartAddress"
          placeholder="智能解析：粘贴或者输入整段文字，自动识别姓名、号码、地址，如：张某某13512345678浙江省杭州市西湖区某某路某某某大厦001号"
        />
      </view>

      <!-- 地址标签 -->
      <view class="single-box">
        <view class="single-item">
          <text class="address-title">地址标签</text>
          <text class="item-tab mr-15rpx" :class="{ 'item-tab-active': form.tag == 1 }" @click="form.tag = 1">
            家
          </text>
          <text class="item-tab mr-15rpx" :class="{ 'item-tab-active': form.tag == 2 }" @click="form.tag = 2">
            公司
          </text>
          <text class="item-tab" :class="{ 'item-tab-active': form.tag == 3 }" @click="form.tag = 3">
            学校
          </text>
        </view>
      </view>

      <!-- 默认地址 -->
      <view class="single-box">
        <view class="single-item flex-1 justify-between">
          <text class="default-title">设置默认地址</text>
          <mt-switch class="switch-default" v-model:checked="form.is_default"></mt-switch>
        </view>
      </view>
    </view>
    <view class="footer-add" v-if="form.id == 0">
      <view class="btn save-btn" @click="save()">保存地址</view>
    </view>
    <view class="footer-set" v-else>
      <view class="btn save-btn" @click="save()">保存地址</view>
      <view class="btn del-btn" @click="del()">删除地址</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import mtSwitch from '@/components/mt-switch/mt-switch.vue';
  import AddressParse from 'zh-address-parse';
  import { ref, reactive, watch, computed } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import { msg } from '@/utils/msg';
  import { getAddress, addAddress, setAddress, delAddress } from '@/api/fans/address';
  import { report } from '@/utils/exception';

  const region = ref<string[]>([]);
  const showRegion = ref<boolean>(false);
  const smartAddress = ref<string>('');
  const form = reactive({
    id: 0,
    receiver: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    address: '',
    tag: 0,
    is_default: 0,
  });

  onLoad((option: any) => {
    form.id = option.id;
    if (form.id > 0) {
      uni.setNavigationBarTitle({ title: '编辑地址' });
      getAddress(form.id)
        .then((res) => {
          form.receiver = res.data.receiver;
          form.phone = res.data.phone;
          form.province = res.data.province;
          form.city = res.data.city;
          form.area = res.data.area;
          form.address = res.data.address;
          form.tag = res.data.tag;
          form.is_default = res.data.is_default;
          region.value = [form.province, form.city, form.area];
        })
        .catch((err) => {
          report(err);
        });
    } else {
      uni.setNavigationBarTitle({ title: '新增地址' });
    }
  });

  // 获取微信地址
  const getWxAddress = () => {
    uni.chooseAddress({
      success(res) {
        form.receiver = res.userName;
        form.phone = res.telNumber;
        form.province = res.provinceName;
        form.city = res.cityName;
        form.area = res.countyName;
        form.address = res.detailInfo;
        region.value = [form.province, form.city, form.area];
      },
      fail(err) {
        console.log(err);
      },
    });
  };

  watch(
    () => smartAddress.value,
    () => {
      const result = AddressParse(smartAddress.value);
      form.receiver = result.name;
      form.phone = result.phone;
      form.address = result.detail;
      form.province = result.province;
      form.city = result.city;
      form.area = result.area;
      if (result.province || result.city || result.area) {
        region.value = [result.province, result.city, result.area];
      }
    }
  );

  const regionStr = computed(() => {
    return region.value.join(' / ');
  });

  const changeRegion = (result: any) => {
    form.province = result.province.name;
    form.city = result.city.name;
    form.area = result.area.name;
    region.value = [form.province, form.city, form.area];
  };

  // 检测表单
  const checkForm = () => {
    if (!form.receiver) {
      msg.error('请输入收件人姓名');
      return false;
    }
    if (!form.phone) {
      msg.error('请输入收件人手机号码');
      return false;
    }
    if (!(form.province && form.city && form.area)) {
      msg.error('请选择地区');
      return false;
    }
    if (!form.address) {
      msg.error('请输入详细地址');
      return false;
    }

    return true;
  };

  // 保存地址
  const save = () => {
    if (!checkForm()) return;

    msg.loading();
    if (form.id == 0) {
      // 新增
      addAddress(form)
        .then((res) => {
          msg.success('地址添加成功');
          setTimeout(() => {
            uni.$emit('reload');
            uni.navigateBack();
          }, 2000);
        })
        .catch((err) => {
          report(err);
        });
    } else {
      // 编辑
      setAddress(form)
        .then((res) => {
          msg.success('地址修改成功');
          setTimeout(() => {
            uni.$emit('reload');
            uni.navigateBack();
          }, 2000);
        })
        .catch((err) => {
          report(err);
        });
    }
  };

  // 删除地址
  const del = () => {
    msg.confirm('确定删除该地址？', () => {
      delAddress(form.id)
        .then((res) => {
          msg.success('地址删除成功');
          setTimeout(() => {
            uni.$emit('reload');
            uni.navigateBack();
          }, 2000);
        })
        .catch((err) => {
          report(err);
        });
    });
  };
</script>

<style lang="scss" scoped>
  $fontSize: 28rpx;

  .main-box {
    margin: 25rpx;

    .single-box,
    .form-box,
    .smart-box {
      margin-bottom: 20rpx;
    }

    .form-box {
      padding: 0 25rpx;
      background: white;
      border-radius: 20rpx;

      .form-item {
        display: flex;
        align-items: center;
        padding: 30rpx 0;

        &:not(:last-child) {
          border-bottom: 1rpx solid #f5f5f5;
        }

        .item-title {
          font-size: $fontSize;
          font-weight: 600;
          width: 160rpx;
          flex: none;
        }

        input {
          font-size: $fontSize;
          margin-right: 10rpx;
          width: 100%;
        }

        .area-zone {
          display: flex;
          align-items: center;
          margin-right: 10rpx;
          font-size: $fontSize;
          justify-content: space-between;
          flex: 1;

          .right-icon {
            position: relative;
            top: 5rpx;
            left: 8rpx;
          }
        }
      }
    }

    .smart-box {
      padding: 20rpx 25rpx;
      background: white;
      border-radius: 20rpx;
      .smart-title {
        display: flex;
        font-size: $fontSize;
        font-weight: 600;
        width: 160rpx;
        flex: none;
        margin-bottom: 18rpx;
      }

      .smart-address {
        width: 100%;
        height: 150rpx;
        border-radius: 20rpx;
        background: #f5f5f5;
        padding: 20rpx 25rpx;
        font-size: $fontSize;
        line-height: 40rpx;
        box-sizing: border-box;
      }
    }

    .single-box {
      display: flex;
      align-items: center;
      padding: 0 25rpx;
      background: white;
      border-radius: 20rpx;
      height: 90rpx;

      .weixin-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex: 1;

        .weixin-title {
          display: flex;
          font-size: $fontSize;
        }
      }

      .single-item {
        display: flex;
        align-items: center;

        .address-title {
          font-size: $fontSize;
          font-weight: 600;
          width: 160rpx;
          flex: none;
        }

        .item-tab {
          display: flex;
          font-size: 26rpx;
          color: #7e7e7e;
          background: #f5f5f5;
          width: 94rpx;
          height: 46rpx;
          border-radius: 30rpx;
          align-items: center;
          justify-content: center;
        }

        .item-tab-active {
          color: white;
          background: #ff4802;
        }

        .default-title {
          font-size: $fontSize;
          font-weight: 600;
          width: 220rpx;
          flex: none;
        }

        .switch-default {
          display: flex;
          flex-direction: row;
          // flex: 1;
          justify-content: flex-end;
        }
      }
    }
  }

  .footer-add {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 110rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background: white;
  }

  .footer-set {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 10rpx 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background: #f5f5f5;
  }

  .btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90%;
    font-size: 26rpx;
    font-weight: 600;
    margin: 10rpx auto;
    padding: 24rpx 0;
    border-radius: 50rpx;
    letter-spacing: 1rpx;
  }

  .save-btn {
    color: white;
    background-image: linear-gradient(to right, #f3204f, #f33720);
    box-shadow: rgba(255, 28, 0, 0.2) 0 5rpx 12rpx;
  }

  .del-btn {
    background-image: linear-gradient(to right, #cacaca, #c3c3c3);
    box-shadow: rgba(46, 46, 46, 0.1) 0 5rpx 12rpx;
  }
</style>
